package com.hyjiacan.tools.apps.apitool.handlers.models


class ApiRequestForm(body: Map<String, Any>) {
    var method: String = ""
    var url: String = ""
    var contentType: String = ""
    var form = mutableMapOf<String, Any>()
    lateinit var body: Any

    var headers = mutableMapOf<String, String>()

    init {
        this.method = body.getValue("method").toString()
        this.url = body.getValue("url").toString()
        this.contentType = body.getValue("contentType").toString()

        // 请求头数据项，通过 formKeys 传递，逗号分隔多个字段的 key
        // 对应的数据使用特定的头前缀 `header_key__`
        val headerKeys = body.getValue("headerKeys").toString().split(',')
        val headers = mutableMapOf<String, String>()
        for (key in headerKeys) {
            headers[key] = body.getValue("header_key__$key").toString()
        }

        this.headers = headers

        if (this.contentType.contains("multipart/form-data") || this.contentType.contains("application/x-www-form-urlencoded")) {
            // 表单数据项，通过 formKeys 传递，逗号分隔多个字段的 key
            // 对应的数据使用特定的头前缀 `form_key__`
            val formKeys = body.getValue("formKeys").toString().split(',')
            val form = mutableMapOf<String, Any>()
            for (key in formKeys) {
                form[key] = body.getValue("form_key__$key")
            }
            this.form = form
        } else {
            // json 或者其它类型，直接加载原始数据
            this.body = body.getValue("rawBody").toString()
        }
    }
}